package com.gupao.javavip.netty.push.client.processor.handler;

import com.gupao.javavip.netty.push.api.Request;
import io.netty.channel.ChannelHandlerContext;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;
import io.netty.util.concurrent.ScheduledFuture;
import lombok.extern.apachecommons.CommonsLog;

import java.util.concurrent.TimeUnit;

@CommonsLog
public class ReceiveMsgRequestClientHandler extends AbstractPushMsgRequestClientHandler {
    private static final Long PULL_MSG_CYCLE = 10L; //拉取消息的执行周期，单位“秒”

    @Override
    protected void whenActive(ChannelHandlerContext ctx) {
        Runnable command = () -> sendRequest(ctx);
        ScheduledFuture<?> future = ctx.channel().eventLoop().scheduleAtFixedRate(command, 0, PULL_MSG_CYCLE, TimeUnit.SECONDS);
    }

    @Override
    protected GenericFutureListener<Future<? super Void>> buildSendListener(Request request) {
        return (writeFuture) -> {
            //消息发送成功
            if (writeFuture.isSuccess()) {
                log.info("拉取推送成功！");
            }
            //消息发送失败
            else {
                log.error("拉取推送失败...");
            }
        };
    }

    @Override
    protected Request buildRequest() {
        return service.buildReceiveRequest();
    }
}
